<template>
	<view class="container">
		<uni-icons type="contact-filled" size="100" color="gray"></uni-icons>
		<button type="primary" class="button" @click="getUserProfile">一键登录</button>
		<text>登录后尽享更多权益</text>
	</view>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
export default {
	name: 'my-login',
	data() {
		return {};
	},
	computed: {
		// 映射
		...mapState('m_user', ['redirectInfo'])
	},
	methods: {
		// 映射
		...mapMutations('m_user', ['saveUserInfo', 'saveToken', 'updateRedirectInfo']),
		// 获取用户信息。每次请求都会弹出授权窗口，用户同意后返回 userInfo
		getUserProfile() {
			const that = this;
			uni.getUserProfile({
				desc: '获取你的昵称、头像、地区及性别',
				success(res) {
					that.saveUserInfo(res.userInfo);
					// 拉取用户成功，调用登录
					uni.login({
						provider: 'weixin',
						success: function(loginRes) {
							if (loginRes.errMsg !== 'login:ok') return uni.$showMsg('登录失败');
							// 调用登录接口
							that.login({
								code: loginRes.code,
								encryptedData: res.encryptedData,
								iv: res.iv,
								rawData: res.rawData,
								signature: res.signature
							});
						},
						fail(err) {
							return uni.$showMsg('登录失败');
						}
					});
				},
				fail(err) {
					if (err.errMsg === 'getUserProfile:fail auth deny') {
						return uni.$showMsg('您取消了登录授权！');
					}
				}
			});
		},
		// 登录
		login(query) {
			// 模拟接口返回
			const res = {
				message: {
					user_id: 23,
					user_email_code: null,
					is_active: null,
					user_sex: '男',
					user_qq: '',
					user_tel: '',
					user_xueli: '本科',
					user_hobby: '',
					user_introduce: null,
					create_time: 1562221487,
					update_time: 1562221487,
					token: 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOjIzLCJpYXQiOjE1NjQ3MzAwNzksImV4cCI6MTAwMTU2NDczMDA3OH0.YPt-XeLnjV-_1ITaXGY2FhxmCe4NvXuRnRB8OMCfnPo'
				},
				meta: {
					msg: '登录成功',
					status: 200
				}
			};
			if (res.meta.status !== 200) return uni.$showMsg('登录失败');
			// 保存token
			this.saveToken(res.message.token);
			// 重定向上一个页面
			this.redirectBack();
		},
		// 重定向上一个页面
		redirectBack() {
			// 判断重定向信息和类型
			if (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {
				const that = this;
				// 跳转至登录页面
				uni.switchTab({
					url: this.redirectInfo.from,
					// 导航成功之后，把 vuex 中的 redirectInfo 对象重置为 null
          complete: () => {
            this.updateRedirectInfo(null)
          }
				});
			}
		}
	}
};
</script>

<style lang="scss">
page {
	background-color: #ffffff;
}
// 外层容器
.container {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	height: 750rpx;
	background-color: #f8f8f8;
	position: relative;

	&::after {
		content: '';
		width: 100%;
		height: 50px;
		background-color: #ffffff;
		position: absolute;
		bottom: 0;
		left: 0;
		border-radius: 100%;
		transform: translateY(50%);
	}

	.button {
		width: 90%;
		border-radius: 25px;
		background-color: #d81e06;
	}
	text {
		margin-top: 10px;
		font-size: 13px;
		color: gray;
	}
}
</style>
